package com.anjoyo.xgh.musicshare.service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.anjoyo.xgh.musicshare.R;
import com.anjoyo.xgh.musicshare.activity.MainActivity;
import com.anjoyo.xgh.musicshare.application.SongApplication;
import com.anjoyo.xgh.musicshare.db.MusicDBhelper;
import com.anjoyo.xgh.musicshare.entry.Song;
import com.anjoyo.xgh.musicshare.util.Constant;
import com.anjoyo.xgh.musicshare.util.Constant.PLAYLIST;
import com.anjoyo.xgh.musicshare.util.Constant.PLAYSTATUS;
import com.anjoyo.xgh.musicshare.util.StringUtil;

public class DownloadService extends Service {

	ArrayList<Task> songTasks = new ArrayList<Task>();
	MyBroadCastReciver reciver;
	MusicDownThread thread;
	NotificationManager manager;
	Notification notification;
	RemoteViews views;
	Context con;
	boolean isdowning = false;
	int i;
	FileBroadCast fileBroadCast;
	TelephonyManager telephonyManager;
	boolean ispaused= false;
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		con = this;
		IntentFilter inf = new IntentFilter();
		inf.addAction(Constant.SERVICE_DOWN);
		inf.addAction(Constant.ACTION_PLAY);
		inf.addAction(Constant.ACTION_PAUSE);
		inf.addAction(Constant.ACTION_AGO);
		inf.addAction(Constant.ACTION_NEXT);
		reciver = new MyBroadCastReciver();
		this.registerReceiver(reciver, inf);

		fileBroadCast = new FileBroadCast();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
		intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
		intentFilter.addDataScheme("file");
		this.registerReceiver(fileBroadCast, intentFilter);

		thread = new MusicDownThread();
		thread.start();
		initNotifation();
		super.onCreate();
		PhoneStateListener phoneStateListener = new PhoneStateListener() {
			@Override
			public void onCallStateChanged(int state, String incomingNumber) {
				super.onCallStateChanged(state, incomingNumber);
				switch (state) {
				case 0://挂断
					if (ispaused) {
						player.start();
						ispaused=false;
					}
					break;
				case 1://来电
					if (player.isPlaying()) {
						player.pause();
						ispaused=true;
					}
					break;
				case 2://去电
					if (player.isPlaying()) {
						player.pause();
						ispaused=true;
					}
					break;
				default:
					break;
				}
			}
		};
		telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		telephonyManager.listen(phoneStateListener,
				PhoneStateListener.LISTEN_CALL_STATE);

	}

	class MyBroadCastReciver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

			String action = intent.getAction();
			Task task;
			if (action.equals(Constant.SERVICE_DOWN)) {
				System.out.println("接收到下载通知");
				task = (Task) intent.getSerializableExtra("task");
				if (!songTasks.contains(task)) {// 如果 队列里面没有下载任务，添加进去，并且 唤醒线程
					songTasks.add(task);
					if (!isdowning) {
						synchronized (thread) {
							thread.notify();
						}
					}
				}
			}
			if (action.equals(Constant.ACTION_PLAY)) {
				int pos = intent.getIntExtra("pos", -1);
				if (pos >= 0 && pos != SongApplication.getInstance().currentpos) {
					SongApplication.getInstance().currentpos = pos;
					PlayMusic();
				} else {
					if (SongApplication.status == PLAYSTATUS.WAITE) {
						PlayMusic();
					} else if (SongApplication.status == PLAYSTATUS.PAUSE) {
						player.start();
						SongApplication.status = PLAYSTATUS.PLAYING;
					} else if (SongApplication.status == PLAYSTATUS.PLAYING) {
						player.pause();
						SongApplication.status = PLAYSTATUS.PAUSE;
					}
				}
			} else if (action.equals(Constant.ACTION_AGO)) {
				AgoMusic();
			} else if (action.equals(Constant.ACTION_NEXT)) {
				NextMusic();
			}
		}
	}

	class MusicDownThread extends Thread {
		@Override
		public void run() {
			super.run();
			while (true) {
				while (songTasks.size() > 0) {
					if (!isdowning) {
						isdowning = true;
						Task task = songTasks.remove(0);
						down_song(task);
					}
				}
				synchronized (this) {
					try {
						this.wait();
						System.out.println("等待");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	public void down_song(final Task task) {
		String songname = task.name;
		String url = Constant.SERVER_IP + ((Song) task.obj).getNet_url();
		File file = new File(Constant.MUSIC_PATH + songname + ".mp3");
		if (!file.exists()) {
			file.getParentFile().mkdirs();
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			if (file.length() > 10) {
				if (((Song) task.obj).isIsfav()) {
					MusicDBhelper dBhelper = new MusicDBhelper(con);
					dBhelper.saveMusic((Song) task.obj, false, true);
					long i = dBhelper.updateoffline(
							((Song) task.obj).getMusicid(), true);
					if (i != 0) {
						System.out.println("离线下载成功，保存成功");
					} else {
						System.out.println("离线下载成功，保存失败");
					}
				}
				isdowning = false;
				System.out.println("此歌已下载！");
				return;
			}
		}
		FinalHttp finalHttp = new FinalHttp();
		((Song) task.obj).setLocal_url(file.getAbsolutePath());
		finalHttp.download(StringUtil.pasekongge(url), file.getAbsolutePath(),
				new AjaxCallBack<File>() {

					@Override
					public void onStart() {
						super.onStart();
						if (((Song) task.obj).isIsfav()) {
							Intent intent = new Intent(
									Constant.ACTION_FAVDOWN_START);
							intent.putExtra("musicid",
									((Song) task.obj).getMusicid());
							sendBroadcast(intent);
						}
					}

					@Override
					public void onLoading(long count, long current) {
						super.onLoading(count, current);
						int pro = (int) ((int) current * 100 / count);
						updateDownPro(pro, task.name);
					}

					@Override
					public void onSuccess(File t) {
						MusicDBhelper dBhelper = new MusicDBhelper(con);
						if (!((Song) task.obj).isIsfav()) {
							long i = dBhelper.saveMusic((Song) task.obj, false,
									true);
							if (i != 0) {
								System.out.println("下载成功，保存成功");
							} else {
								System.out.println("下载成功，保存失败");
							}
							manager.cancel(100);
						} else {
							dBhelper.saveMusic((Song) task.obj, false, true);
							long i = dBhelper.updateoffline(
									((Song) task.obj).getMusicid(), true);
							if (i != 0) {
								System.out.println("离线下载成功，保存成功");
							} else {
								System.out.println("离线下载成功，保存失败");
							}
							manager.cancel(100);
							Intent intent = new Intent(
									Constant.ACTION_FAVDOWN_END);
							intent.putExtra("musicid",
									((Song) task.obj).getMusicid());
							sendBroadcast(intent);
						}
						isdowning = false;
						System.out.println("发送广播");
						scanSDfile(Constant.MUSIC_PATH);
						super.onSuccess(t);
					}
				});
	}

	public void initNotifation() {
		manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notification = new Notification(android.R.drawable.stat_sys_download,
				"正在下载", System.currentTimeMillis());
		views = new RemoteViews(getPackageName(), R.layout.download_notify);
		notification.contentIntent = PendingIntent.getActivity(this, 100,
				new Intent(this, MainActivity.class),
				PendingIntent.FLAG_UPDATE_CURRENT);
		notification.contentView = views;
		notification.flags = Notification.FLAG_NO_CLEAR;
		notification.defaults = Notification.DEFAULT_LIGHTS;
	}

	public void updateDownPro(int pro, String name) {
		views.setTextViewText(R.id.musicname, "正在下载:" + name + "  " + pro + "%");
		views.setProgressBar(R.id.downloadpro, 100, pro, false);
		manager.notify(100, notification);
	}

	/*-----------------------------------播放控制-------------------------------------*/
	/* 实例变量 */
	// PLAYSTATUS status = PLAYSTATUS.WAITE;
	// Song currentsong;
	ArrayList<Song> songs = SongApplication.getInstance().currentlist;
	MediaPlayer player = SongApplication.getInstance().player;
	PLAYLIST nowpalylist;

	/*-----------------------------------------------------------------------------*/
	// 播放
	private void PlayMusic() {
		if (songs.size() < 1) {
			ToastMsg("暂无本地歌曲可播放");
			return;
		}
		SongApplication.currentsong = songs
				.get(SongApplication.getInstance().currentpos);
		if (SongApplication.currentsong.isIsnetMusic()) {
			if (SongApplication.currentsong.isIsdoffline()) {
				player.reset();
				try {
					player.setDataSource(SongApplication.currentsong
							.getLocal_url());
				} catch (Exception e) {
					e.printStackTrace();
				}
				try {
					player.prepare();
				} catch (Exception e) {
					e.printStackTrace();
				}
				player.start();
				SongApplication.status = PLAYSTATUS.PLAYING;
			} else {
				player.reset();
				String url = Constant.SERVER_IP
						+ StringUtil.pasekongge(SongApplication.currentsong
								.getNet_url());
				System.out.println("网络歌曲播放url:" + url);
				try {
					player.setDataSource(url);
				} catch (Exception e) {
					e.printStackTrace();
				}
				player.prepareAsync();
				player.setOnPreparedListener(new OnPreparedListener() {

					@Override
					public void onPrepared(MediaPlayer mp) {
						player.start();
						SongApplication.status = PLAYSTATUS.PLAYING;
					}
				});
				ToastMsg("歌曲正在缓冲中……");
			}

		} else {
			player.reset();
			try {
				player.setDataSource(SongApplication.currentsong.getLocal_url());
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				player.prepare();
			} catch (Exception e) {
				e.printStackTrace();
			}
			player.start();
			SongApplication.status = PLAYSTATUS.PLAYING;
		}
		sendBroadcast(new Intent(Constant.ACTION_UPDATE_MUSIC));
		player.setOnCompletionListener(new OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				sendBroadcast(new Intent(Constant.ACTION_NEXT));
			}
		});
	}

	// 暂停
	public void PauseMusic() {
		player.pause();
	}

	// 前一首
	public void AgoMusic() {
		if (SongApplication.getInstance().currentpos == 0) {
			SongApplication.getInstance().currentpos = songs.size() - 1;
		} else {
			SongApplication.getInstance().currentpos--;
		}
		PlayMusic();
	}

	// 后一首
	public void NextMusic() {
		if (SongApplication.getInstance().currentpos == (songs.size() - 1)) {
			SongApplication.getInstance().currentpos = 0;
		} else {
			SongApplication.getInstance().currentpos++;
		}
		PlayMusic();
	}

	/*-----------------------------------播放控制-------------------------------------*/

	public void ToastMsg(String msg) {
		Toast.makeText(this, msg, 0).show();
	}

	/*----------------------------------文件扫描操作----------------------------------------*/
	public void scanSDfile(String path) {
		// 扫描指定的一个文件(目录)广播 --速度快
		Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		intent.setData(Uri.fromFile(new File(path)));
		sendBroadcast(intent);

		// 扫描全局--速度慢
		// sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
		// Uri.parse("file://"
		// + Environment.getExternalStorageDirectory()
		// .getAbsolutePath())));
	}

	class FileBroadCast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) {
				System.out.println("收到了文件扫描广播start");
				// SongApplication.getInstance().LoadLocalSongs();
			}
			if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
				System.out.println("收到了文件扫描广播end");
				SongApplication.getInstance().LoadLocalSongs();
			}

		}
	}

}
